<template>
  <div class="app-container">
  
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            v-hasPerm="['goods:cate:add']"
            type="success"
            icon="plus"
            @click="handleOpenDialog()"
          >
            新增
          </el-button>
          <!-- <el-button
            v-hasPerm="['goods:cate:delete']"
            type="danger"
            :disabled="selectIds.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button> -->
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="Lists"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="150" />
        <el-table-column prop="name" label="名称"  />
        <el-table-column prop="image" label="图片" >
          <template #default="{ row }">
            <el-image
              style="width: 50px; height: 50px; border-radius: 50%"
              :src="'https://clip.xxauesa.com/'+row.image"
              :preview-src-list="['https://clip.xxauesa.com/'+row.image]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="150" />
        <!-- <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="createTime" label="创建时间" width="220" />

        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">

            <el-button
              v-hasPerm="['goods:cate:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id,scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['goods:cate:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData" :rules="rules" label-width="120px">
        
        <el-form-item label="商品分类" prop="managerId" required>
          <el-select v-model="formData.managerId" placeholder="请选择商品分类">
            <el-option :label="'无上级'" :value="0"></el-option>
            <el-option 
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="名称" prop="classifyName">
          <el-input v-model="formData.classifyName" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="图片">
          <SingleImageUpload v-model="formData.classifyImage" />
        </el-form-item>
        
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>


        <!-- <el-form-item label="状态" >
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->
      
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "分类",
  inheritAttrs: false,
});

import GoodsAPI, { CateVO, CateForm } from "@/api/system/goods.api";

// const queryFormRef = ref();
const FormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<any>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const Lists = ref<CateVO[]>();
const formData = reactive<CateForm>({
  classifyId: undefined,
  classifyName: "",
  classifyImage: "",
  sort: 1,
  status: 1,
  managerId: 0, // 分类ID
});

const rules = reactive({
  classifyName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

const categories = ref();

GoodsAPI.getCateList().then((res) => {
   categories.value = res
})


// 查询
function handleQuery() {
  console.log(queryParams)
  loading.value = true;
  GoodsAPI.getCateList()
    .then((res) => {
      Lists.value = res;
    })
    .catch((error) => {
      console.error("查询分类失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });

  loading.value = false;
}

// 重置查询
// function handleResetQuery() {
//   queryFormRef.value.resetFields();
//   handleQuery();
// }

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开新增弹窗
 *
 * @param Id ID
 */
async function handleOpenDialog(Id?:string,data?:any) {

  dialog.visible = true;
  if (Id) {
    dialog.title = "修改";

    const editForm = {
      classifyId: data?.id,
      classifyName: data?.name,
      classifyImage: data?.image,
      sort: data?.sort,
      status: data?.status,
      managerId: data?.pid||0, // 分类ID
    }

    Object.assign(formData, editForm);
  } else {
    dialog.title = "新增";
  }
}

// 提交表单
function handleSubmit() {
  FormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.classifyId) {

        const json = {
          classifyId: formData.classifyId,
          classifyName: formData.classifyName,
          classifyImage: formData.classifyImage,
          sort: formData.sort,
          status: formData.status,
          managerId: formData.managerId
        }

        GoodsAPI.updateCate(json)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        GoodsAPI.createCate(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
     
    }
  });
}

// 删除
function handleDelete(Id?: number) {
  const Ids = [Id || selectIds.value].join(",");

  if (!Ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      const dataJson = {
        "dataId": Ids //数据ID(会员配置列表获得）
      }
      GoodsAPI.deleteByIdsCate(dataJson)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();

  formData.classifyId = '';
  formData.status = 1;
  formData.sort = 1;
  formData.classifyName = "";
  formData.classifyImage = "";
  formData.managerId = 0; // 分类ID
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
